package com.atguigu.chapter07.timer;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/6/15 9:03
 */
public class Flink01_Timer_Project {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        // 定时器: 有两种 基于处理时间和基于事件时间
        
        env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(data[0], Long.parseLong(data[1]), Integer.valueOf(data[2]));
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((ws, ts) -> ws.getTs())
            )
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                private Long timerTs;
                private Integer lastVc;
                boolean isFirst = true;
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    /*
                    第一个水位来了之后要注册定时器,
                    后面的水位如果相比上次是上升, 则什么都不做
                    如果是下降: 删除定时器, 并且重新注册一个新的定时器
                     */
                    if (isFirst) {
                        System.out.println("第一条数据");
                        // 注册定时器
                        timerTs = ctx.timestamp() + 5000;
                        isFirst = false;
                        
                        ctx.timerService().registerEventTimeTimer(timerTs);
                        
                    } else {
                        // 不是第一条
                        if (value.getVc() - lastVc <= 0) { // 水位没有上升
                            System.out.println("水位下降或不变...");
                            // 1.上次上次注册的定时器
                            ctx.timerService().deleteEventTimeTimer(timerTs);
                            // 2. 重新注册一个新的定时器
                            timerTs = ctx.timestamp() + 5000;
                            ctx.timerService().registerEventTimeTimer(timerTs);
                        }else{
                            System.out.println("水位上升...");
                        }
                    }
                    // 不管这次数据是否第一条, 都要保存这次的水位, 以供下次使用
                    lastVc = value.getVc();
                }
                
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<String> out) throws Exception {
                    out.collect(ctx.getCurrentKey() + " 连续5s水位上升, 发出红色预警...");
                }
            })
            .print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
